package com.ant.storage.service.impl;

import com.ant.storage.common.ResultVo;
import com.ant.storage.dto.DingDto;
import com.ant.storage.dto.GoodsPoolDto;
import com.ant.storage.dto.MergeDto;
import com.ant.storage.handler.AntException;
import com.ant.storage.mapper.*;
import com.ant.storage.pojo.*;
import com.ant.storage.service.*;
import com.ant.storage.utils.DateFormat;
import com.ant.storage.utils.DingDingUtil;
import com.ant.storage.utils.RandomUtil;
import com.ant.storage.vo.CommodityVo;
import com.ant.storage.vo.PurchaseVo;
import com.ant.storage.wechat.WeChatUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taobao.api.ApiException;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author melon
 * @since 2022-03-17
 */
@Service
public class GoodsPoolServiceImpl extends ServiceImpl<GoodsPoolMapper, GoodsPool> implements IGoodsPoolService {

    @Resource
    private IGoodsPoolCommodityService goodsPoolCommodityService;

    @Resource
    private CommodityMapper commodityMapper;

    @Resource
    private IAbilityService abilityService;

    @Resource
    private ISubscribeService subscribeService;

    @Resource
    private IPurchaseOrdersService purchaseOrdersService;

    @Resource
    private IAuditListService auditListService;

    @Resource
    SubscribeMapper subscribeMapper;

    @Autowired(required = false)
    AllocationMapper allocationMapper;

    @Autowired
    IUserService userService;

    @Autowired
    IDepartmentService departmentService;

    @Autowired
    IGoodsPoolAndSubscribeService goodsPoolAndSubscribeService;

    @Resource
    public InventoryMapper inventoryMapper;

    @Resource
    public InventoryLogMapper inventoryLogMapper;

    @Autowired
    public ServletContext servletContext;

    @Autowired
    public IWarehouseService warehouseService;

    @Autowired
    public IApprovalMsgService approvalMsgService;

    @Override
    public PageInfo<GoodsPool> getGoodsPoolList(GoodsPoolDto dto) {
        UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
        PageHelper.startPage(dto.getPageIndex(), dto.getPageSize());
        QueryWrapper<GoodsPool> wrapper = new QueryWrapper<>();
        if (dto.getDepartmentId() != null) {
            wrapper.lambda().eq(GoodsPool::getDepartmentId, dto.getDepartmentId());
        }
        if (StringUtils.isNotEmpty(dto.getSubscribeNumber())) {
            wrapper.lambda().like(GoodsPool::getSubscribeNumber, dto.getSubscribeNumber().trim());
        }
        if (dto.getProposerId() != null) {
            wrapper.lambda().eq(GoodsPool::getProposerId, dto.getProposerId());
        }
        if (dto.getApplyStatus() != null) {
            wrapper.lambda().eq(GoodsPool::getApplyStatus, dto.getApplyStatus());
        }
        if (userInfo.getRoles() == null) {
            wrapper.lambda().and(qr -> qr.eq(GoodsPool::getProposerId, userInfo.getNameId()).or()
                    .eq(GoodsPool::getPurchaserId, userInfo.getNameId()));
        } else if (userInfo.getRoles() != null && userInfo.getRoles().equals("warehouse")) {
            wrapper.lambda().in(GoodsPool::getProposerId, userInfo.getNameId());
        } else if (userInfo.getRoles() != null && userInfo.getRoles().equals("admin")) {
            wrapper.lambda().in(GoodsPool::getCityId, userInfo.getCityId());
        } else if (userInfo.getRoles() != null && userInfo.getRoles().equals("price")) {
            wrapper.lambda().in(GoodsPool::getProposerId, userInfo.getNameId());
        } else {
            if (dto.getCityId() != null && dto.getCityId().size() > 0) {
                wrapper.lambda().in(GoodsPool::getCityId, Arrays.asList(dto.getCityId()));
            }
        }
        if (dto.getTime() != null && dto.getTime().size() != 0) {
            wrapper.ge("creation_time", dto.getTime().get(0) + " 00:00:00");
            wrapper.le("creation_time", dto.getTime().get(1) + " 23:59:59");
        }
        wrapper.eq("is_delete", 1);
        wrapper.orderByDesc("id");
        List<GoodsPool> goodsPoolList = this.baseMapper.selectList(wrapper);
        goodsPoolList.stream().map(item -> {
            List<CommodityVo> commodityVo = commodityMapper.commodityAndGoodList(item.getId(), null);
            item.setCommodityList(commodityVo);
            item.setDepartment(departmentService.getDepName(item.getDepartmentId()));
            return item;
        }).collect(Collectors.toList());
        PageInfo<GoodsPool> pageInfo = new PageInfo<>(goodsPoolList);
        return pageInfo;
    }

    @Override
    public PageInfo<GoodsPool> getAppletGoodsPoolList(GoodsPoolDto dto) {
        PageHelper.startPage(dto.getPageIndex(), dto.getPageSize());
        QueryWrapper<GoodsPool> wrapper = new QueryWrapper<>();
        if (dto.getDepartmentId() != null) {
            wrapper.lambda().eq(GoodsPool::getDepartmentId, dto.getDepartmentId());
        }
        if (StringUtils.isNotEmpty(dto.getSubscribeNumber())) {
            wrapper.lambda().like(GoodsPool::getSubscribeNumber, dto.getSubscribeNumber().trim());
        }
        if (dto.getProposerId() != null) {
            wrapper.lambda().eq(GoodsPool::getProposerId, dto.getProposerId());
        }
        if (dto.getApplyStatus() != null) {
            wrapper.lambda().eq(GoodsPool::getApplyStatus, dto.getApplyStatus());
        }
        wrapper.lambda().and(qr -> qr.eq(GoodsPool::getProposerId, dto.getProposerId()));

        if (dto.getTime() != null && dto.getTime().size() != 0) {
            wrapper.ge("creation_time", dto.getTime().get(0) + " 00:00:00");
            wrapper.le("creation_time", dto.getTime().get(1) + " 23:59:59");
        }
        wrapper.eq("is_delete", 1);
        wrapper.orderByDesc("id");
        List<GoodsPool> goodsPoolList = this.baseMapper.selectList(wrapper);
        goodsPoolList.stream().map(item -> {
            List<CommodityVo> commodityVo = commodityMapper.commodityAndGoodList(item.getId(), null);
            item.setCommodityList(commodityVo);
            List<AuditList> auditList = auditListService.list(new QueryWrapper<AuditList>()
                    .eq("parent_id", item.getId()).eq("process_type", "goodsPool"));
            item.setAuditList(auditList);
            item.setDepartment(departmentService.getDepName(item.getDepartmentId()));
            return item;
        }).collect(Collectors.toList());
        PageInfo<GoodsPool> pageInfo = new PageInfo<>(goodsPoolList);
        return pageInfo;
    }

    @Override
    public GoodsPool getAppletGoodsPoolDetailsById(Integer id) {
        GoodsPool goodsPoolList = this.baseMapper.selectOne(new QueryWrapper<GoodsPool>().eq("id", id));
        if (goodsPoolList != null) {
            List<CommodityVo> collect = commodityMapper.commodityAndGoodId(id);
            goodsPoolList.setCommodityList(collect);
        }
        return goodsPoolList;
    }

    @Override
    public GoodsPool getGoodsPoolDetailsById(Integer id) {
        GoodsPool goodsPoolList = this.baseMapper.selectOne(new QueryWrapper<GoodsPool>().eq("id", id));
        List<GoodsPoolCommodity> list = goodsPoolCommodityService.list(
                new QueryWrapper<GoodsPoolCommodity>().eq("goods_pool_id", id));
        List<CommodityVo> collect = list.stream().map(items -> {
            CommodityVo commodityVo = commodityMapper.commodityAndGood(items.getId());
            return commodityVo;
        }).collect(Collectors.toList());
        goodsPoolList.setCommodityList(collect);
        List<AuditList> auditList = auditListService.list(new QueryWrapper<AuditList>()
                .eq("parent_id", id).eq("process_type", "goodsPool"));
        goodsPoolList.setAuditList(auditList);

        ApprovalMsg approvalMsgs = approvalMsgService.getOne(new QueryWrapper<ApprovalMsg>()
                .eq("parent_id", id).eq("approval_type", "goodsPool"));
        if(approvalMsgs!=null){
            goodsPoolList.setApprovalMsgList(approvalMsgs);
        }else{
            goodsPoolList.setApprovalMsgList(null);
        }
        return goodsPoolList;
    }

    /**
     * 保存申请单
     *
     * @param goodsPool
     * @param bindingResult
     * @return
     * @throws NullPointerException
     */
    @Override
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @Transactional(rollbackFor = Exception.class)
    public ResultVo saveGoodsPool(GoodsPool goodsPool, BindingResult bindingResult) throws NullPointerException,
            AntException {
        synchronized (this) {
            // 参数校验
            if (bindingResult.hasErrors()) {
                throw new AntException(bindingResult.getFieldError().getDefaultMessage());
            } else {
                UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
                // 判断是自定义物品数据
                goodsPool.setSubscribeNumber("SQ" + RandomUtil.getOrderNumbers(this.baseMapper.selectLastID()));
                // 进度 0  已提交  1 审核通过  2 审核拒绝
                goodsPool.setApplyStatus(goodsPool.getIsApproved() == 1 ? 1 : 2);
                // 处理状态 0 未处理  1 已处理  2取消"
                goodsPool.setProposerId(userInfo.getNameId());
                goodsPool.setCityId(userInfo.getCityId());
                goodsPool.setDepartmentId(userInfo.getDepId());
                goodsPool.setStatus(0);
                goodsPool.setCreatorBy(userInfo.getNameId().toString());
                goodsPool.setCreationTime(new Date());
                goodsPool.setSplitting(goodsPool.getSplitting() != null ? goodsPool.getSplitting() : 0);
                goodsPool.setDeliveryTime(goodsPool.getDeliveryTime() == null ? new Date() :
                        goodsPool.getDeliveryTime());
                this.baseMapper.insert(goodsPool);
                if (goodsPool.getCommodityList().size() != 0) {
                    List<CommodityVo> list = goodsPool.getCommodityList();
                    //批量添加
                    List<GoodsPoolCommodity> goodsPoolCommodities = list.stream().map((item) -> {
                        Integer cid = addComd(item, goodsPool.getCityId(), goodsPool.getCreatorBy());
                        GoodsPoolCommodity goodsList = new GoodsPoolCommodity();
                        BeanUtils.copyProperties(item, goodsList);
                        goodsList.setCommodityId(cid == null ? item.getCommodityId() : cid);
                        goodsList.setCommodityAmount(new BigDecimal(item.getCommodityAmount()));
                        goodsList.setCommodityLinks(item.getCommodityLinks());
                        goodsList.setPayType(item.getPayType());
                        goodsList.setChannel(item.getChannel());
                        goodsList.setGoodsPoolId(goodsPool.getId());
                        goodsList.setCommodityPrice(item.getCommodityPrice().toString() == "" || item.getCommodityPrice() == null ? new BigDecimal("0") : item.getCommodityPrice());
                        return goodsList;
                    }).collect(Collectors.toList());
                    // 批量添加
                    goodsPoolCommodityService.saveBatch(goodsPoolCommodities);
                    if (goodsPool.getIsApproved() == 1) {
                        // 判断是否为空
                        if (goodsPool.getApproval().size() == 0 || goodsPool.getApproval() == null) {
                            throw new AntException("请选择审批人员");
                        }
                        AuditList auditList = new AuditList();
                        auditList.setParentId(goodsPool.getId());
                        auditList.setName(userInfo.getNameId().toString());
                        auditList.setProcessType("goodsPool");
                        auditList.setCreationTime(new Date());
                        // 添加审核记录
                        for (String str : goodsPool.getApproval()) {
                            auditList.setNameId(str);
                            auditList.setTypes("1");
                            auditListService.save(auditList);
                        }
                        if (goodsPool.getNotify().size() == 0 || goodsPool.getNotify() == null) {
                            throw new AntException("请选择抄送人");
                        }
                        for (String str2 : goodsPool.getNotify()) {
                            auditList.setNameId(str2);
                            auditList.setTypes("2");
                            auditListService.save(auditList);
                        }
                        String str = addWeChatData(goodsPool);
                        // 修改审批id
                        UpdateWrapper<GoodsPool> updateWrapper = new UpdateWrapper<GoodsPool>().set(
                                "process_instance_id", str).eq("id", goodsPool.getId());
                        this.update(updateWrapper);
                        ApprovalMsg msg=new ApprovalMsg();
                        msg.setParentId(goodsPool.getId());
                        msg.setApprovalType("goodsPool");
                        msg.setApprovalUser(userInfo.getUserName());
                        msg.setApprovalUserId(userInfo.getNameId());
                        msg.setSpNo(str);
                        msg.setCreationTime(new Date());
                        approvalMsgService.save(msg);
                        return ResultVo.success("保存成功", goodsPool);
                    } else {
                        adoptApply(goodsPool.getId());
                    }
                    return ResultVo.success("保存成功", goodsPool);
                } else {
                    return ResultVo.fail("商品不能为空");
                }
            }
        }
    }

    /**
     * 判断是否存在物品
     *
     * @return
     * @throws Exception
     */
    public Integer addComd(CommodityVo commodity, Integer cityId, String uid) {
        Commodity cmd = new Commodity();
        Commodity selectOne = commodityMapper.selectOne(new QueryWrapper<Commodity>().eq("commodity_name",
                commodity.getCommodityName()).eq("is_delete", 1));
        if (selectOne == null) {
            cmd.setCommodityBarCode("ZDY" + commodityMapper.selectLastID());
            cmd.setCommodityName(commodity.getCommodityName());
            cmd.setCommodityUnits(commodity.getCommodityUnits());
            cmd.setCommodityPrice(commodity.getCommodityPrice());
            cmd.setCommodityType(commodity.getCommodityType() == null ? 43 : commodity.getCommodityType());
            cmd.setCityId(cityId);
            cmd.setCommoditySpecification(commodity.getCommoditySpecification());
            cmd.setCreationBy(uid);
            cmd.setCreationTime(new Date());
            commodityMapper.insert(cmd);
            return cmd.getCommodityId();
        } else {
            return selectOne.getCommodityId();
        }
    }
    /**
     * 提交钉钉审批
     *
     * @param dto
     * @return
     */
    @SneakyThrows
    @Transactional(rollbackFor = Exception.class)
    public String addDingDing(DingDto dto) throws ApiException {
        dto.setAccess_token(DingDingUtil.obtainToken());
        String process_instance_id = DingDingUtil.OldGoodeAppalyAndApprove(dto);
        return process_instance_id;
    }

    @SneakyThrows
    @Transactional(rollbackFor = Exception.class)
    public String addWeChatData(GoodsPool dto) throws AntException {
        InvoiceInfo info = new InvoiceInfo();
        UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
        info.setWeChat(userInfo.getWeChat());
        info.setUserName(userInfo.getUserName());
        info.setInvoiceName("物资采购申请");
        info.setReimbursementTypeText("物资采购申请");
        info.setApproval(dto.getApproval());
        info.setNotify(dto.getNotify());
        info.setInvoicePrice(new BigDecimal(dto.getPrice().toString()));
        info.setStartTime(DateFormat.simpleDateFormats(dto.getDeliveryTime()));
        info.setEndTime(DateFormat.simpleDateFormats(dto.getDeliveryTime()));
        info.setInvoiceNotes(dto.getRemark());
        info.setAccountName(null);
        info.setAccountNumber(null);
        info.setAccountBank(null);
        List<ReimburseDetail> list = new ArrayList<>();
        if (dto.getCommodityList() != null && dto.getCommodityList().size() > 0) {
            dto.getCommodityList().forEach(item -> {
                ReimburseDetail detail = new ReimburseDetail();
                detail.setProjectName(item.getCommodityName());
                detail.setProjectAmount(item.getCommodityAmount());
                detail.setProjectUnit(item.getCommodityUnits());
                detail.setProjectPrice(item.getCommodityPrice());
                list.add(detail);
            });
        }
        info.setDetailList(list);
        String str = WeChatUtils.launchWeChatData(info);
        return str;
    }


    @Override
    public ResultVo updateGoodsPool(GoodsPoolDto goodsPoolDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            throw new AntException(bindingResult.getFieldError().getDefaultMessage());
        } else {
            GoodsPool goodsPool = new GoodsPool();
            BeanUtils.copyProperties(goodsPoolDto, goodsPool);
            //goodsPool.setCreationTime(new Date());
            if (goodsPoolDto.getId() != null || goodsPoolDto.getId() != 0) {
                goodsPoolCommodityService.remove(new QueryWrapper<GoodsPoolCommodity>().eq("", goodsPoolDto.getId()));
                List<GoodsPoolCommodity> goodsPoolCommodities = goodsPoolDto.getGoodsList().stream().map((item) -> {
                    GoodsPoolCommodity goodsList = new GoodsPoolCommodity();
                    BeanUtils.copyProperties(item, goodsList);
                    goodsList.setCommodityAmount(item.getCommodityAmount());
                    goodsList.setGoodsPoolId(goodsPoolDto.getId());
                    return goodsList;
                }).collect(Collectors.toList());
                // 批量添加
                goodsPoolCommodityService.saveBatch(goodsPoolCommodities);
                this.baseMapper.updateById(goodsPool);
                return ResultVo.success("修改成功");
            }
            return ResultVo.success("修改失败");
        }
    }

    /**
     * 申购申请钉钉通过申请
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVo adoptApply(Integer id) {
        GoodsPool goodsPool = this.baseMapper.selectOne(new QueryWrapper<GoodsPool>().eq("id", id));
        if (goodsPool.getId() != null) {
            GoodsPool g = new GoodsPool();
            g.setId(id);
            g.setApplyStatus(2);
            g.setStatus(2);
            this.baseMapper.updateById(g);
            // 生成采购单
            List<GoodsPoolCommodity> commodityList =
                    goodsPoolCommodityService.list(new QueryWrapper<GoodsPoolCommodity>()
                            .eq("goods_pool_id", id));
            BigDecimal counts = new BigDecimal("0.00");

            for (int i = 0; i < commodityList.size(); i++) {
                BigDecimal bigDecimal =
                        new BigDecimal(commodityList.get(i).getCommodityAmount().toString()).multiply
                                (commodityList.get(i).getCommodityPrice() == null ? new BigDecimal("0") :
                                        commodityList.get(i).getCommodityPrice());
                counts = counts.add(bigDecimal);
            }
            Integer ids = 0;
            if (goodsPool.getProposerId() == 1941) {
                ids = 1;
            }
            Subscribe subscribe = new Subscribe();
            subscribe.setParentId(goodsPool.getId());
            subscribe.setCityId(goodsPool.getCityId());
            subscribe.setDepartmentId(goodsPool.getDepartmentId());
            subscribe.setSubscribeNumber("CG" + goodsPool.getSubscribeNumber().substring(2));
            subscribe.setPurchaseType(goodsPool.getApplyType().toString());
            subscribe.setPurchaserId(goodsPool.getPurchaserId() != null ? goodsPool.getPurchaserId().toString() : null);
            subscribe.setTotal(commodityList.size());
            subscribe.setPrice(counts);
            subscribe.setProcessState(2);
            subscribe.setStatus(ids == 0 ? "0" : "3");
            subscribe.setDeliveryTime(goodsPool.getDeliveryTime());
            //applyType
            subscribe.setIsMerge(goodsPool.getApplyType() != 18 ? 1 : 0);
            subscribe.setStatus("0");
            subscribe.setProposerId(goodsPool.getProposerId());
            subscribe.setCreatorBy(goodsPool.getCreatorBy());
            subscribe.setCreationTime(new Date());
            subscribeService.save(subscribe);

            // 采购清单
            Integer finalIds = ids;
            List<PurchaseOrders> ordersList = commodityList.stream().map(item -> {
                PurchaseOrders orders = new PurchaseOrders();
                System.out.println(orders);
                orders.setOrdersNumber(goodsPool.getSubscribeNumber().substring(2));
                orders.setDepartmentId(goodsPool.getDepartmentId());
                orders.setParentId(subscribe.getId());
                orders.setGoodsPoolCommodityId(item.getId());
                orders.setGoodsTotalPrice(new BigDecimal(item.getCommodityAmount().toString()).multiply(item
                        .getCommodityPrice() == null ? new BigDecimal("0") : item.getCommodityPrice()));
                orders.setPaymentMethod(item.getPayType());
                orders.setChannel(item.getChannel());
                orders.setGoodsStatus(finalIds == 0 ? 0 : 2);
                orders.setPurchaserId(goodsPool.getPurchaserId() != null ?
                        Integer.valueOf(subscribe.getPurchaserId()) : null);
                orders.setModifierBy("1");
                orders.setCreationTime(new Date());
                return orders;
            }).collect(Collectors.toList());
            purchaseOrdersService.saveBatch(ordersList);
            return ResultVo.success("申请通过");
        } else {
            return ResultVo.fail("不存在!!!");
        }
    }

    @Override
    public Integer getprocessInstanceIdById(String processInstanceId) {
        GoodsPool pool = this.baseMapper.selectOne(new QueryWrapper<GoodsPool>()
                .eq("process_instance_id", processInstanceId));
        if (pool != null) {
            adoptApply(pool.getId());
            return pool.getId();
        }
        return null;
    }

    /**
     * 小程序查询合并申购详情
     *
     * @param ids
     * @return
     */
    @Override
    public ResultVo getMergeApply(Integer[] ids) {
        List<GoodsPool> list = this.list(new QueryWrapper<GoodsPool>().in("id", Arrays.asList(ids)));
        //  [138,139]
        List<GoodsPool> goodsPoolId = list.stream().map(item -> {
            List<GoodsPoolCommodity> goods_pool_id =
                    goodsPoolCommodityService.list(new QueryWrapper<GoodsPoolCommodity>()
                            .eq("goods_pool_id", item.getId()));
            List<CommodityVo> collect = goods_pool_id.stream().map(items -> {
                CommodityVo commodityVo = commodityMapper.commodityAndGood(items.getId());
                return commodityVo;
            }).collect(Collectors.toList());
            item.setCommodityList(collect);
            return item;
        }).collect(Collectors.toList());
        // 是否要发起请款审批
        return ResultVo.success("采购单生成成功", goodsPoolId);
    }

    /**
     * 小程序完成签收
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVo signInCompleted(Integer id) {
        UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
        GoodsPool goodsPool = this.baseMapper.selectOne(new QueryWrapper<GoodsPool>().eq("id", id));
        //  Integer warehouseId = getwarehouseId(goodsPool.getCityId());
        if (goodsPool.getId() != null) {
            this.update(new UpdateWrapper<GoodsPool>().set("status", 5).in("id", id));
            subscribeService.update(new UpdateWrapper<Subscribe>().set("status", 4)
                    .set("handlers", userInfo.getNameId())
                    .set("handler_time", new Date())
                    .eq("parent_id", id));
            // 修改实际的入库数量
            List<GoodsPoolCommodity> goodsPoolId =
                    goodsPoolCommodityService.list(new QueryWrapper<GoodsPoolCommodity>().eq("goods_pool_id", id));
            goodsPoolId.stream().map(item -> {
                goodsPoolCommodityService.update(new UpdateWrapper<GoodsPoolCommodity>().set("commodity_number",
                        item.getCommodityAmount()).eq("goods_pool_id", id));
                purchaseOrdersService.update(new UpdateWrapper<PurchaseOrders>().set("goods_status",
                        "3").eq("goods_pool_commodity_id", item.getId()));
                return item;
            }).collect(Collectors.toList());
            return ResultVo.success("签收成功");
        } else {
            return ResultVo.fail("不存在!!!");
        }
    }


    /**
     * 查询仓库
     *
     * @return
     */
    private Integer getwarehouseId(Integer cityId) {
        Warehouse warehouse = warehouseService.getOne(new QueryWrapper<Warehouse>().eq("city_id", cityId));
        if (warehouse != null) {
            return warehouse.getId();
        }
        return 1;
    }


    /**
     * 计算价格
     *
     * @return
     */
    private BigDecimal calculatePrice(Integer inventoryId) {
        List<InventoryLog> list = inventoryLogMapper.selectList(new QueryWrapper<InventoryLog>()
                .eq("inventory_id", inventoryId).eq("stock_state", 1));
        int buySum =
                list.stream().map(item -> Integer.valueOf(item.getGoodsAmount())).mapToInt(Integer::intValue).sum();
        double v =
                list.stream().map(a -> new BigDecimal(String.valueOf(a.getGoodsAmount())).multiply(new BigDecimal(String.valueOf(a.getGoodsPrice())))).reduce(BigDecimal.ZERO, BigDecimal::add).doubleValue();
        BigDecimal divide = BigDecimal.valueOf(v).divide(BigDecimal.valueOf(buySum), 3, BigDecimal.ROUND_HALF_DOWN);
        return divide;
    }

    /**
     * 添加入库日志记录
     */
    public void insertLoginLog(Integer inventoryId, PurchaseVo vo, Integer id) {
        InventoryLog log = new InventoryLog();
        log.setWarehouseId(vo.getWarehouseId());
        log.setInventoryId(inventoryId);
        log.setGoodsAmount(vo.getCommodityNumber()); // 入库实际数量
        log.setGoodsPrice(vo.getCommodityPrice()); // 入库实际数量
        log.setStockState(1); // 入库
        log.setSubscribeId(id); // 采购单id
        log.setRemark("采购入库");
        log.setPurchaseOrdersId(vo.getId());
        log.setCreatorBy(vo.getModifierBy());
        log.setCreationTime(new Date());
        inventoryLogMapper.insert(log);
    }


    @Override
    public AuditList selectIsAudit(String processInstanceId, String user_id) {
        System.out.println(processInstanceId + "---" + user_id);
        GoodsPool goodsPools = this.getOne(new QueryWrapper<GoodsPool>()
                .eq("process_instance_id", processInstanceId));
        if (goodsPools != null) {
            AuditList parentId = auditListService.getOne(new QueryWrapper<AuditList>().eq("parent_id",
                    goodsPools.getId()).eq("process_type", "goodsPool").eq("types", "1")
                    .eq("name_id", user_id));
            if (parentId != null) {
                return parentId;
            }
            return null;
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVo mergeApply(MergeDto dto) {
        List<GoodsPool> list = this.list(new QueryWrapper<GoodsPool>().in("id", Arrays.asList(dto.getId())));
        if (list.size() == 0) {
            return ResultVo.fail("不存在!!!");
        }
        //计算总金额
        Integer counst = 0;
        BigDecimal counts = new BigDecimal("0.00");
        for (int i = 0; i < list.size(); i++) {
            List<GoodsPoolCommodity> commodityList =
                    goodsPoolCommodityService.list(new QueryWrapper<GoodsPoolCommodity>()
                            .eq("goods_pool_id", list.get(i).getId()));
            counst = counst + commodityList.size();
            for (int j = 0; j < commodityList.size(); j++) {
                BigDecimal bigDecimal =
                        new BigDecimal(commodityList.get(j).getCommodityAmount().toString()).multiply(commodityList.get(j).getCommodityPrice());
                counts = counts.add(bigDecimal);
            }
        }

        // 生成采购单号
        Subscribe subscribe = new Subscribe();
        subscribe.setParentId(null);
        subscribe.setCityId(list.get(0).getCityId());
        subscribe.setDepartmentId(dto.getDepartmentId());
        subscribe.setSubscribeNumber(RandomUtil.getOrderNumbers(subscribeMapper.selectLastID()));
        subscribe.setPurchaseType(dto.getPurchaseType());
        //        subscribe.setPurchaserId(list.get(0).getPurchaserId() != null ? list.get(0).getPurchaserId() :
        //                dto.getPurchaserId());
        subscribe.setProposerId(list.get(0).getProposerId());// dto.getProposerId()
        subscribe.setTotal(counst);
        subscribe.setPayType(dto.getPaymentMethod().toString());
        subscribe.setPrice(counts);
        subscribe.setTotalPrice(dto.getPrice());
        subscribe.setProcessState(2);
        subscribe.setStatus("1");
        subscribe.setCreatorBy(list.get(0).getProposerId().toString());
        subscribe.setCreationTime(new Date());
        subscribeService.save(subscribe);

        List<Integer> collect = list.stream().map(GoodsPool::getId).collect(Collectors.toList());
        List<GoodsPoolAndSubscribe> collect1 = collect.stream().map(item -> {
            GoodsPoolAndSubscribe goodsPoolAndSubscribe = new GoodsPoolAndSubscribe();
            goodsPoolAndSubscribe.setGoodsPoolId(item);
            goodsPoolAndSubscribe.setSubscribeId(subscribe.getId());
            return goodsPoolAndSubscribe;
        }).collect(Collectors.toList());
        goodsPoolAndSubscribeService.saveBatch(collect1);

        List<GoodsPoolCommodity> goodsPoolId = goodsPoolCommodityService.list(new QueryWrapper<GoodsPoolCommodity>()
                .in("goods_pool_id", Arrays.asList(dto.getId())));
        List<CommodityVo> commodityList = goodsPoolId.stream().map(c -> {
            Commodity selectOne = commodityMapper.selectOne(new QueryWrapper<Commodity>().in("commodity_id",
                    c.getCommodityId()));
            CommodityVo commodityVo = new CommodityVo();
            commodityVo.setGoodsPoolCommodityId(c.getId());
            commodityVo.setGoodsPoolId(c.getGoodsPoolId());
            commodityVo.setCommodityId(selectOne.getCommodityId());
            commodityVo.setCommodityName(selectOne.getCommodityName());
            commodityVo.setCommodityPrice(c.getCommodityPrice());
            commodityVo.setCommodityAmount(c.getCommodityAmount().toString());
            return commodityVo;
        }).collect(Collectors.toList());

        // 采购清单
        List<PurchaseOrders> ordersList = commodityList.stream().map(item -> {
            GoodsPool id = this.getOne(new QueryWrapper<GoodsPool>()
                    .eq("id", item.getGoodsPoolId()));
            PurchaseOrders orders = new PurchaseOrders();
            orders.setOrdersNumber(subscribe.getSubscribeNumber());
            orders.setParentId(subscribe.getId());
            orders.setDepartmentId(id.getDepartmentId());
            orders.setPaymentMethod(dto.getPaymentMethod());
            orders.setGoodsPoolCommodityId(item.getGoodsPoolCommodityId());
            orders.setGoodsTotalPrice(new BigDecimal(item.getCommodityAmount()).multiply(item.getCommodityPrice()));
            orders.setGoodsStatus(0);
            orders.setPurchaserId(Integer.valueOf(subscribe.getPurchaserId()));
            orders.setChannel(dto.getChannel());
            orders.setIsSettlement(0);
            orders.setModifierBy("1");
            orders.setCreationTime(new Date());
            return orders;
        }).collect(Collectors.toList());
        purchaseOrdersService.saveBatch(ordersList);

        this.update(new UpdateWrapper<GoodsPool>().set("status", 2).in("id", Arrays.asList(dto.getId())));


        Ability one = abilityService.getOne(new QueryWrapper<Ability>()
                .eq("ability_key", "Nail_Approval"));
        if (dto.getIsApproved() == 1) {
            if (dto.getApproval().size() == 0) {
                throw new AntException("请选择审批人员");
            }
            if (dto.getNotify().size() == 0) {
                throw new AntException("请选择审批人员");
            }
            // 发起钉钉审批
            // 通过 getUserId()
            DingDto dingDto = new DingDto();
            dingDto.setOriginator_userid(dto.getUserId());
            try {
                Long personneDeplList = DingDingUtil.getPersonneDepld(dto.getUserId(), DingDingUtil.obtainToken());
                Integer depid = personneDeplList.intValue();
                dingDto.setDeptId(depid);
            } catch (ApiException e) {
                e.printStackTrace();
            }
            //  dto.setDeptId(149215742);
            dingDto.setId(subscribe.getId());
            dingDto.setApprover_userid(dto.getApproval());
            dingDto.setCc_userId(dto.getNotify());
            dingDto.setList(commodityList);
            //dingDto.setCity(dto.getCity());
            //dingDto.setDepartment(dto.get());
            dingDto.setRemarks(dto.getRemarks());
            //采购申请钉钉审批
            try {
                System.out.println("dto:" + dto);
                String process_instance_ids = addDingDing(dingDto);
                // 修改审批id
                UpdateWrapper<GoodsPool> updateWrapper = new UpdateWrapper<GoodsPool>().set(
                        "process_instance_id", process_instance_ids).eq("id", dto.getId());
                this.update(updateWrapper);
                return ResultVo.success("采购单生成成功", subscribe.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ResultVo.success("采购单生成成功", subscribe.getId());
    }


    @Override
    public PageInfo<GoodsPool> getAppletsGoodsPoolList(GoodsPoolDto goodsPoolDto) {
        PageHelper.startPage(goodsPoolDto.getPageIndex(), goodsPoolDto.getPageSize());
        QueryWrapper<GoodsPool> wrapper = new QueryWrapper<>();
        if (goodsPoolDto.getDepartmentId() != null) {
            wrapper.lambda().eq(GoodsPool::getDepartmentId, goodsPoolDto.getDepartmentId());
        }
        if (goodsPoolDto.getPurchaserId() != null) {
            wrapper.lambda().eq(GoodsPool::getPurchaserId, goodsPoolDto.getPurchaserId());
        }
        if (goodsPoolDto.getApplyStatus() != null) {
            wrapper.lambda().eq(GoodsPool::getApplyStatus, goodsPoolDto.getApplyStatus());
        }
        if (StringUtils.isNotEmpty(goodsPoolDto.getSubscribeNumber())) {
            wrapper.lambda().eq(GoodsPool::getSubscribeNumber, goodsPoolDto.getSubscribeNumber());
        }
        wrapper.orderByDesc("id");
        PageInfo<GoodsPool> pageInfo = new PageInfo<>(this.baseMapper.selectList(wrapper));
        List<GoodsPool> order_sn = pageInfo.getList().stream().map(item -> {
            List<GoodsPoolCommodity> list = goodsPoolCommodityService.list(
                    new QueryWrapper<GoodsPoolCommodity>().eq("goods_pool_id", item.getId()));
            List<CommodityVo> collect = list.stream().map(items -> {
                CommodityVo commodityVo = commodityMapper.commodityAndGood(items.getId());
                return commodityVo;
            }).collect(Collectors.toList());
            item.setCommodityList(collect);
            return item;
        }).collect(Collectors.toList());

        pageInfo.setList(order_sn);
        return pageInfo;
    }

    @Override
    public ResultVo getDistributionGoodsPool(Integer nameId, Integer[] ids) {

        if (nameId == null) {
            return ResultVo.fail("采购员id不能为空");
        } else if (ids == null && ids.length == 0) {
            return ResultVo.fail("商品池id不能为空");
        } else {
            List<Integer> list = Arrays.asList(ids);
            List<GoodsPool> collect = new ArrayList<>();

            list.stream().map(item -> {
                GoodsPool pool = new GoodsPool();
                pool.setPurchaserId(nameId);
                pool.setSplitting(1);
                pool.setId(item);
                collect.add(pool);
                return item;
            }).collect(Collectors.toList());
            this.updateBatchById(collect);
            return ResultVo.success("分配成功");
        }
    }
}
